package com.oliver.proxy.midjourney.application.service;

import com.oliver.proxy.midjourney.domain.aggregate.TaskAggregate;
import com.oliver.proxy.midjourney.domain.entity.TaskList;
import com.oliver.proxy.midjourney.domain.entity.InsertPoint;
import com.oliver.proxy.midjourney.domain.repository.TaskAggregateRepository;
import com.oliver.proxy.midjourney.domain.service.TaskDomainService;
import com.oliver.proxy.midjourney.domain.valueobject.TaskType;
import com.oliver.proxy.midjourney.interfaces.dto.CreateTaskRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TaskApplicationService {
    private final TaskAggregateRepository taskAggregateRepository;
    private final TaskDomainService taskDomainService;

    public TaskApplicationService(TaskAggregateRepository taskAggregateRepository,
                                TaskDomainService taskDomainService) {
        this.taskAggregateRepository = taskAggregateRepository;
        this.taskDomainService = taskDomainService;
    }

    @Transactional
    public Long createTask(CreateTaskRequest request) {
        TaskList taskList = new TaskList();
        taskList.setTaskType(request.getTaskType());
        taskList.setTaskCategory(request.getTaskCategory());
        taskList.setTaskGenQty(request.getTaskGenQty());
        taskList.setTaskPrompt(request.getTaskPrompt());
        taskList.setTaskStatus(0);

        if (TaskType.TYPE_0.getValue().equals(request.getTaskType())) {
            taskList.setTaskSwitchNum(null);
        } else {
            taskList.setTaskSwitchNum(request.getTaskSwitchNum());
        }

        TaskAggregate taskAggregate = new TaskAggregate(taskList);
        taskDomainService.validateInsertPoints(taskAggregate, request.getInsertPoints());

        Long taskId = taskAggregateRepository.saveAggregate(taskAggregate);
        taskList.setTaskId(taskId);

        if (TaskType.TYPE_0.getValue().equals(request.getTaskType()) && request.getInsertPoints() != null) {
            List<InsertPoint> insertPoints = taskDomainService.createInsertPoints(taskId, request.getInsertPoints());
            taskAggregateRepository.saveInsertPoints(insertPoints);
        }

        return taskId;
    }

    public TaskAggregate getTask(Long taskId) {
        return taskAggregateRepository.findById(taskId);
    }

    public List<TaskAggregate> getAllTasks() {
        return taskAggregateRepository.findAll();
    }

    public List<TaskAggregate> getTasksByCategory(String category) {
        return taskAggregateRepository.findByCategory(category);
    }

    @Transactional
    public void updateTask(TaskAggregate taskAggregate) {
        taskAggregateRepository.update(taskAggregate);
    }

    @Transactional
    public void deleteTask(Long taskId) {
        taskAggregateRepository.delete(taskId);
    }
}